package message.handler;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import net.VirtualQueue;

import message.Packet;

public class PersistentMessageHandler implements Runnable {

	public static final String folder = "Cloud";
	private static String extension = ".olivaw";
	private static String fileNameSeparator = "#";

	private String packetRappresentation;
	private String receiver;

	public PersistentMessageHandler(String packetRappresentation,
			String receiver) {
		this.packetRappresentation = packetRappresentation;
		this.receiver = receiver;
	}

	public PersistentMessageHandler(Packet packet, String receiver){
		this(packet.toXML(), receiver);
	}

	@Override
	public synchronized void run() {
		try {
			setUp();
			createXMLFile();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void setUp() throws IOException {
		File cloudDirectory = new File(folder);
		if (cloudDirectory.exists() && cloudDirectory.isDirectory())
			return;
		cloudDirectory.mkdir();
		cloudDirectory.createNewFile();
	}

	private void createXMLFile() throws IOException {
		String fileName = this.receiver + fileNameSeparator +getCardinality()
				+ PersistentMessageHandler.extension;
		File xmlFile = new File(new File(folder), fileName);
		xmlFile.setWritable(true);
		
		FileWriter fstream = new FileWriter(xmlFile);
		BufferedWriter out = new BufferedWriter(fstream);
		
		out.write(packetRappresentation);
		out.close();
		xmlFile.createNewFile();
		
		VirtualQueue vq = VirtualQueue.obtainVirtualQueue();
		vq.storeMessage(fileName);
	}

	private int getCardinality() {
		File cloudDirectory = new File(folder);
		File[] fileList = cloudDirectory.listFiles();

		int count = -1;
		for (File current : fileList) {
			String postReceiver = current.getName().split(PersistentMessageHandler.fileNameSeparator)[1];
			String preExtension = postReceiver
					.split(PersistentMessageHandler.extension)[0];

			int id = Integer.parseInt(preExtension);
			if (id > count)
				count = id;
		}
		return count + 1;
	}

}
